"use client"
import React, { useEffect, useState } from 'react';
import { Button, DatePicker, Input, Menu, message, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
import type { MenuProps, TableProps } from 'antd';
import {
  CheckCircleFilled,
  EditFilled,
  VerticalAlignTopOutlined,
  DeleteFilled,
  SearchOutlined,
  RedoOutlined,
  ZoomInOutlined,
  UploadOutlined,
  DownloadOutlined,
  RetweetOutlined,
  DeliveredProcedureOutlined,
  BorderOutlined,
  QuestionCircleFilled,
  SortAscendingOutlined,
  InsertRowAboveOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import Myform from '../sj/myform'
import * as API from '../../axios/http'

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
interface DataType {
  id: number
  key: string
  name: string
  Customer: string
  stage: string
  bjnum: number
  price: number
  time: number
  days: number
}


const App: React.FC = () => {

  function datas() {
    useEffect(() => {
      API.getZzt().then(res => {
        // console.log(res)
        setdata(res)
      })
    }, [])

  }
  datas()
  const [itemobj, setitemobj] = useState({})

  const [title, settitle] = useState('添加'); //添加商机标题
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '商机标题',
      dataIndex: 'name',
      render: (name) => <div style={{ color: 'rgb(0,121,254)' }}>{name}</div>,
    },
    {
      title: '关联客户',
      dataIndex: 'Customer',
      render: (Customer) => <div style={{ color: 'rgb(0,121,254)' }}>{Customer}</div>,
    },
    {
      title: '商机阶段',
      dataIndex: 'stage'
    },
    {
      title: '报价记录',
      dataIndex: 'bjnum',
      render: (bjnum) => <div style={{ color: 'rgb(0,121,254)' }}>{bjnum}条</div>,
    },
    {
      title: '报价总金额',
      dataIndex: 'price',
      render: (price) => <div>￥{price.toFixed(2)}</div>,
    },
    {
      title: '最后跟进',
      dataIndex: 'time',
      render: (time) => <div>{new Date(time).toLocaleString()}</div>,
    },
    {
      title: '未跟进天数',
      dataIndex: 'days'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle" style={{ color: 'rgb(0,121,254)' }}>
          <div onClick={() => {
            console.log(record);
            const obj = {
              ...record,
              time: new Date().getTime()
            }
            const res = API.http_editZzt(obj).then(res => {
              setdata(obj)
            })
          }}><CheckCircleFilled />跟进</div>
          <div onClick={() => {
            showModal()
            settitle('编辑')
            setitemobj(record)
          }}><EditFilled />编辑</div>
          <div onClick={() => {
            let index = data.findIndex(item => item.id === record.id)
            console.log(index, '/下标索引');
            if (index == 0) {
              alert('已经是第一条了')
              return
            }
            data.splice(index, 1)
            setdata([record, ...data])
          }}><VerticalAlignTopOutlined />置顶</div>

          <Popconfirm
            title="Delete"
            description="确定要删除这条吗?"
            onConfirm={() => {
              //删除功能：根据id删除
              API.http_deleteZzt(record.id).then(() => {
                setdata(data.filter((item) => item.id !== record.id))
                message.success('删除成功');
              })
            }}
            onCancel={() => {
            }}
            okText="是"
            cancelText="否"
          >
            <div ><DeleteFilled />删除</div>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  //表格数据
  let [data, setdata] = useState<DataType[]>([])
  //三级导航数据
  type MenuItem = Required<MenuProps>['items'][number];

  const items: MenuItem[] = [
    {
      key: 'a',
      label: (
        <a href="/page/sj" target='_parent' rel="noopener noreferrer">
          全部商机
        </a>
      ),
    },
    {
      key: 'b',
      label: (
        <a href="/page/sj" target="_parent" rel="noopener noreferrer">
          我的商机
        </a>
      ),
    },
    {
      key: 'c',
      label: (
        <a href="/" target="_parent" rel="noopener noreferrer">
          下属商机
        </a>
      ),
    },
    {
      key: 'd',
      label: (
        <a href="/" target="_parent" rel="noopener noreferrer">
          下属写作
        </a>
      ),
    },
    { 
      key: 'e',
      label: (
        <a href="/" target="_parent" rel="noopener noreferrer">
          成交商机
        </a>
      ),
    },
    {
      key: 'f',
      label: (
        <a href="/" target="_parent" rel="noopener noreferrer">
          我的协作
        </a>
      )
    }
  ];



  const [current, setCurrent] = useState('mail');

  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
    setCurrent(e.key);
  };
  //多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,

    ]
  };
  //添加气泡框

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //1
  const [name, setname] = useState('')
  const [value, setvalue] = useState('关联客户')
  const [values, setvalues] = useState('商机阶段')


  return (
    <>
      <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} style={{ marginBottom: '20px' }} />

      <div>
        <Space style={{ marginBottom: '40px' }}>
          <Input placeholder="搜索商机标题" value={name} onChange={(e) => setname(e.target.value)} />

          <Select

            style={{ width: 150 }}
            value={value}
            onChange={(e) => setvalue(e)}
            options={[
              { value: '深圳市亿恩科技有限公司', label: '深圳市亿恩科技有限公司' },
              { value: '广州市云启智联科技有限公司', label: '广州市云启智联科技有限公司' },
              { value: '上海市星耀智研科技有限公司', label: '上海市星耀智研科技有限公司' },
              { value: '成都市鸿途智汇科技有限公司', label: '成都市鸿途智汇科技有限公司' },
            ]}
          />

          <Select

            style={{ width: 150 }}
            value={values}
            onChange={(e) => setvalues(e)}
            options={[
              { value: '初步洽谈', label: '初步洽谈' },
              { value: '需求调研', label: '需求调研' },
            ]}
          />

          <DatePicker placeholder='预计签单日期' />
          <Button type="primary" onClick={() => {
            const obj = { name, value, values }
            API.http_getzzt(obj).then((res) => {
              setdata(res)
            })
          }}><SearchOutlined />查询</Button>
          <Button onClick={() => {
            //
            setname('')
            setvalue('')
            setvalues('')
            API.getZzt().then((res) => {
              setdata(res)
            })
            alert('重置成功')
            setTimeout(() => {
            }, 100);

          }}><ReloadOutlined />重置</Button>
          <Button style={{ color: 'rgb(0,121,254)' }}><ZoomInOutlined />高级搜索</Button>
        </Space>

        <div style={{ marginBottom: '20px' }}>
          <Space>
            <Button type="primary" onClick={() => {
              showModal()
              settitle('添加')
            }}>
              添加
            </Button>
            <Button onClick={() => { alert("导入成功") }}><DownloadOutlined />导入</Button>
            <Button onClick={() => { alert("导出成功") }}> <UploadOutlined />导出</Button>
            <Button onClick={() => { alert("转移商机成功") }}><RetweetOutlined />转移商机</Button>
            <Button onClick={() => { alert("添加协作成功") }}><DeliveredProcedureOutlined />添加协作</Button>
            <Select
              defaultValue='发送短信'
              style={{ width: 150 }}
              options={[
                { value: '1', label: '1' },
              ]}
            />
            <Button style={{ marginLeft: '250px' }}><BorderOutlined />跟进模式<QuestionCircleFilled /></Button>
            <Button><SortAscendingOutlined />排序</Button>
            <Button><InsertRowAboveOutlined />列表</Button>
          </Space>
        </div>


        <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
          <Myform title={title} setdata={setdata} itemobj={itemobj} handleOk={handleOk} key={new Date().getTime()} />
        </Modal>

      </div>
      <Table<DataType> rowSelection={rowSelection} bordered columns={columns} dataSource={data} pagination={{ defaultPageSize: 7 }} />
    </>
  )
};

export default App;